package com.tianji.learning.utils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @description
 * @author: ZXX-挚爱
 * @time: 2023/7/24 23:47
 */
@Slf4j
@Data
public class DelayTask<D> implements Delayed {

    private D data;
    private Long deadlineNanos;


    public DelayTask(D data, Duration delayTime) {
        this.data = data;
        this.deadlineNanos = System.nanoTime()+delayTime.toNanos();
    }


    @Override
    public long getDelay(TimeUnit unit) {

        long convertNanoTime = unit.convert(Math.max(0, deadlineNanos - System.nanoTime()), TimeUnit.NANOSECONDS);
        log.debug("转换时间为:{}",convertNanoTime);
        return convertNanoTime;

    }

    @Override
    public int compareTo(Delayed o) {
        long l=getDelay(TimeUnit.NANOSECONDS)- o.getDelay(TimeUnit.NANOSECONDS);
        log.debug("时间为:{}",l);

        if (l >0) {
            return 1;
        }else if (l<0){
            return  -1;
        }else {
            return 0;
        }
    }

    /**
     * 获取
     * @return data
     */
    public D getData() {
        return data;
    }

    /**
     * 设置
     * @param data
     */
    public void setData(D data) {
        this.data = data;
    }

    /**
     * 获取
     * @return deadlineNanos
     */
    public Long getDeadlineNanos() {
        return deadlineNanos;
    }

    /**
     * 设置
     * @param deadlineNanos
     */
    public void setDeadlineNanos(Long deadlineNanos) {
        this.deadlineNanos = deadlineNanos;
    }

    public String toString() {
        return "DelayTask{data = " + data + ", deadlineNanos = " + deadlineNanos + ", log = " + log + "}";
    }
}
